package com.spgf.model.dao.util;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import android.annotation.SuppressLint;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Environment;
import android.util.Log;

@SuppressLint("SdCardPath")
public class CustomSQLiteOpenHelper extends SQLiteOpenHelper {

	protected static final String	DATABASE_NAME			= "economizedb.db";

	protected static final String	DATABASE_NAME_SCRIPT	= "economizedb.sql";
	protected static final String	DATABASE_NAME_TXT		= "economizedb.txt";
	private static final int		DATABASE_VERSION		= 1;

	public static String			DB_PATH_EXTERNO			= Environment.getExternalStorageDirectory() + "/Android/";
	protected static String			DB_PATH_INTERNO			= "/data/data/com.spgf.controller/databases/";

	// private Context context;
	private SQLiteDatabase			dbQuery;

	public CustomSQLiteOpenHelper(final Context context) {
		super(context, DATABASE_NAME, null, DATABASE_VERSION);
		// this.context = context;
	}

	@Override
	public synchronized void close() {
		if (dbQuery != null) {
			dbQuery.close();
		}
		super.close();
	}

	@Override
	public void onCreate(final SQLiteDatabase db) {

		try {
			InputStream is = new FileInputStream(DB_PATH_EXTERNO + DATABASE_NAME_TXT);

			InputStreamReader isr = new InputStreamReader(is);
			BufferedReader br = new BufferedReader(isr);

			String sql = br.readLine();

			while (sql != null) {

				Log.w("SYSOUT", sql);

				db.execSQL(sql);
				sql = br.readLine();
			}

		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLiteException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	public void onUpgrade(final SQLiteDatabase db, final int arg1, final int arg2) {
		onCreate(db);
	}

}
